from django.core.urlresolvers import reverse
from datetime import date
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.http import HttpResponse, HttpResponseRedirect, Http404

from event.forms import *
from event.models import *

try:
  from projects import event_tasks as event_tasks
except ImportError:
  event_tasks = None

def event_form(request):
  '''
  Used for creating a new event.
  '''
  event = Event()
  
  if request.POST:
    form = EventForm(data=request.POST, instance=event)
    if form.is_valid():
      form.save()
      if event_tasks:
        objective_id = 33
        owner_id = 1
        target_date = date.today()
        type_id = 11
        event_tasks.add_event_deliverable(event.name, objective_id, owner_id, target_date, type_id)
      return HttpResponseRedirect(reverse('event_event_detail', args=(event.id,)))
    else:
      request.user.message_set.create(message='Please check your data')
  else:
    form = EventForm(instance=event)
    
  return render_to_response('event/form/event.html', {'form':form}, context_instance=RequestContext(request))
  
def session_form(request, session_id=None):
  if session_id:
    session = get_object_or_404(Session, id=session_id)
  else:
    session = Session()

  if request.POST:    
    form = SessionForm(data=request.POST, instance=session)

    if form.is_valid():
      form.save()
      return HttpResponseRedirect(reverse('session_detail', args=(session.id,)))
    else:
      request.user.message_set.create(message='Please check your data.')
  else:
    form = SessionForm(instance=session)

  return render_to_response('event/form/session.html', {'form':form}, context_instance=RequestContext(request))


